<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */

namespace App\Admin\Excel\src;

use App\Admin\Repositories\PointOrder;
use App\Admin\Repositories\UserBeanPackage;
use App\Models\Express;
use App\Models\GroupOrder;
use App\Models\GroupShipment;
use App\Models\PointShipment;
use App\Models\ProductOrder;
use App\Models\ProductShipment;
use App\Models\User;
use App\Models\UserBeanPackages;
use App\Service\Notifications\NotificationService;
use DateTime;
use Dcat\Admin\Actions\HasActionHandler;
use Dcat\EasyExcel\Contracts\Sheet as SheetInterface;
use Dcat\EasyExcel\Excel;
use Exception;

class ImportImplementation
{
    use HasActionHandler;

    protected $model;

    protected $input;

    protected $info;

    protected $data;

    protected $err;

    /**
     * @return mixed
     */
    public function getInput()
    {
        return $this->input;
    }

    /**
     * @param mixed $input
     */
    public function setInput($input): void
    {
        $this->input = $input;
    }

    /**
     * @return string[]
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * @param string[] $model
     */
    public function setModel($model)
    {
        $this->model = $model;
    }

    public function import(array $input)
    {
        $input = collect($input);
        $this->setModel($input->get('name'));
        $this->setInput($input);
        if ($input->has('file') && $input->has('name')) {
            $file = $input->get('file');
            $file = storage_path('app/upload_excel/' . $file);
            $this->task($file);

            if (filled($this->err)) {
                admin_error('以下存在错误!', $this->err->implode(', '));
                return $this->response()
                    ->timeout(60)
                    ->error('以下存在错误!' . $this->err->implode(', '))
                    ->refresh();
            }
            return $this->response()
                ->timeout(60)
                ->success('批量添加完成!')
                ->refresh();
        }
        return false;
    }

    public static function make()
    {
        return new static();
    }

    protected function task($files)
    {
        Excel::import($files)->each(function (SheetInterface $sheet) {
            $chunkSize = 10;
            $sheet->chunk($chunkSize, function ($collection) {
                switch ($this->getModel()) {
                    case GroupOrder::class:
                        $this->groupOrder($collection);
                        break;
                    case ProductOrder::class:
                        $this->ProductOrder($collection);
                        break;
                    case PointOrder::class:
                        $this->PointOrder($collection);
                        break;
                    case UserBeanPackage::class:
                        $this->UserBean($collection);
                        break;

                }
            });
        });
    }

    protected function groupOrder($collection)
    {
        $collection->each(function ($item) {
            $shipment = GroupShipment::with(['order' => function ($query) {
                $query->with('productBrief');
            }])->findOrFail($item['ID']);
            if ($shipment->method == 1) {
                $kd = Express::query()->where('code', strtoupper($item['快递公司编号']))->value('id');
                if (!$kd) {
                    $this->err = collect($this->err)->push(sprintf('无效的快递公司编号:%s,ID:%s', $item['快递公司编号'], $item['ID']));
                    return;
                }
                $shipment->express_id = $kd;
                $shipment->tracking_number = $item['运单号'];
            }
            $shipment->status = $item['状态'];
            if (filled($item['发货时间'])) {
                $s = DateTime::createFromFormat('Y-m-d H:i:s', $item['发货时间'])->format('Y-m-d H:i:s');
            } else {
                $s = now()->toDateTimeString();
            }
            if ($s == 0) {
                $this->err = collect($this->err)->push('无效的发货时间格式！');
                return;
            }

            $shipment->shipped_at = $s;
            if ($shipment->status == 1) {
                $shipment->order->status = 4;
                $user = User::query()->find($shipment->user_id);
                NotificationService::make()->OrderNotify($user, $shipment->order, "已于{$s}发货,请注意查收！", 2);
            } else {
                $shipment->order->status = 3;
            }

            try {
                $shipment->push();
            } catch (Exception $e) {
                $this->err = $e->getMessage();
            }
        });
    }

    private function PointOrder($collection)
    {
        $collection->each(function ($item) {
            $shipment = PointShipment::with(['order' => function ($query) {
                $query->with('productBrief');
            }])->findOrFail($item['ID']);
            if ($shipment->method == 1) {
                $kd = Express::query()->where('code', strtoupper($item['快递公司编号']))->value('id');
                if (!$kd) {
                    $this->err = collect($this->err)->push(sprintf('无效的快递公司编号:%s,ID:%s', $item['快递公司编号'], $item['ID']));
                    return;
                }
                $shipment->express_id = $kd;
                $shipment->tracking_number = $item['运单号'];
            }
            $shipment->status = $item['状态'];
            if (filled($item['发货时间'])) {
                if ($item['发货时间'] instanceof DateTime) {
                    $s = $item['发货时间']->format('Y-m-d H:i:s');
                } else {
                    $s = DateTime::createFromFormat('Y-m-d H:i:s', $item['发货时间'])->format('Y-m-d H:i:s');
                }
                if ($s == 0) {
                    $this->err = collect($this->err)->push('无效的发货时间格式！');
                    return;
                }
            } else {
                $s = now()->toDateTimeString();
            }
            $shipment->shipped_at = $s;
            if ($shipment->status == 1) {
                $shipment->order->status = 4;
                $user = User::query()->find($shipment->user_id);
                NotificationService::make()->OrderNotify($user, $shipment->order, "您的积分商品，已于{$s}发货,请注意查收！", 1);
            } else {
                $shipment->order->status = 3;
            }

            try {
                $shipment->push();
            } catch (Exception $e) {
                $this->err = $e->getMessage();
            }
        });
    }

    private function ProductOrder($collection)
    {
        $collection->each(function ($item) {
            $shipment = ProductShipment::with(['order' => function ($query) {
                $query->with('productBrief');
            }])->findOrFail($item['ID']);
            if ($shipment->method == 1) {
                $kd = Express::query()->where('code', strtoupper($item['快递公司编号']))->value('id');
                if (!$kd) {
                    $this->err = collect($this->err)->push(sprintf('无效的快递公司编号:%s,ID:%s', $item['快递公司编号'], $item['ID']));
                    return;
                }
                $shipment->express_id = $kd;
                $shipment->tracking_number = $item['运单号'];
            }
            $shipment->status = $item['状态'];
            if (filled($item['发货时间'])) {
                if ($item['发货时间'] instanceof DateTime) {
                    $s = $item['发货时间']->format('Y-m-d H:i:s');
                } else {
                    $s = DateTime::createFromFormat('Y-m-d H:i:s', $item['发货时间'])->format('Y-m-d H:i:s');
                }
                if ($s == 0) {
                    $this->err = collect($this->err)->push('无效的发货时间格式！');
                    return;
                }
            } else {
                $s = now()->toDateTimeString();
            }
            $shipment->shipped_at = $s;
            if ($shipment->status == 1) {
                $shipment->order->status = 4;
                $user = User::query()->find($shipment->user_id);
                NotificationService::make()->OrderNotify($user, $shipment->order, "已于{$s}发货,请注意查收！", 1);
            } else {
                $shipment->order->status = 3;
            }

            try {
                $shipment->push();
            } catch (Exception $e) {
                $this->err = $e->getMessage();
            }
        });
    }

    private function UserBean($collection)
    {
        $collection->each(function ($item) {
            $shipment = UserBeanPackages::query()->findOrFail($item['ID']);
            $kd = Express::query()->where('code', strtoupper($item['快递公司编号']))->value('id');
            if (!$kd) {
                $this->err = collect($this->err)->push(sprintf('无效的快递公司编号:%s,ID:%s', $item['快递公司编号'], $item['ID']));
                return;
            }
            $shipment->express_id = $kd;
            $shipment->tracking_number = $item['运单号'];

            $shipment->status = $item['状态'];
            if (filled($item['发货时间'])) {
                if ($item['发货时间'] instanceof DateTime) {
                    $s = $item['发货时间']->format('Y-m-d H:i:s');
                } else {
                    $s = DateTime::createFromFormat('Y-m-d H:i:s', $item['发货时间'])->format('Y-m-d H:i:s');
                }
                if ($s == 0) {
                    $this->err = collect($this->err)->push('无效的发货时间格式！');
                    return;
                }
            } else {
                $s = now()->toDateTimeString();
            }
            $shipment->shipped_at = $s;
            if ($shipment->status == 1) {
                $shipment->status = 1;
                $user = User::query()->find($shipment->user_id);
                NotificationService::make()->OrderNotify($user, $shipment, "礼包已于{$s}发货,请注意查收！", 1);
            } else {
                $shipment->status = 0;
            }

            try {
                $shipment->push();
            } catch (Exception $e) {
                $this->err = $e->getMessage();
            }
        });
    }
}
